package com.zretc.letter.service;

import com.zretc.api.pojo.Letter;
import com.zretc.letter.dao.LetterMapper;
import com.zretc.letter.dao.LetterUserMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class LetterService {
    private static final Logger log= LogManager.getLogger(LetterService.class);
    @Autowired
    private LetterMapper letterMapper;

    @Autowired
    private LetterUserMapper letterUserMapper;
//    @Autowired
//    private WebSocketServer webSocketServer;
    public List<Letter> queryLettersByAmount(Integer index, Integer pageNum, Integer userId)
    {
        return letterMapper.getLettersByAmount(index, pageNum, userId);
    }
    public Letter queryLetterById(Integer id,Integer userId)
    {
        if(!updateIsReadOfLetter(userId, id))log.info("站内信改已读失败");
        return letterMapper.getLetterById(id);
    }
    public boolean publishLetterToAll(Letter letter)
    {
//        WebSocketServer.sendMessage("您有1条新通知待查看");
        boolean result=letterMapper.addSingleRecord(letter)==1 && letterUserMapper.addRecordsJoinUser(letter.getId())!=0;
        return result;
    }
    public boolean publishLetterToSingleUser(Letter letter,Integer userId)
    {
//        WebSocketServer.sendMessage("您有1条新通知待查看");
        boolean result=letterMapper.addSingleRecord(letter)==1 && letterUserMapper.addSingleRecord(userId,letter.getId())==1;
        return result;
    }
    public boolean updateIsReadOfLetter(Integer userId,Integer letterId)
    {
        return letterUserMapper.updateIsReadToTrue(userId, letterId)==1;
    }
    public boolean deleteSingleLetterOfUser(Integer userId,Integer letterId)
    {
        return letterUserMapper.deleteSingleRecord(userId, letterId)==1;
    }
//    public void sayHello(String msg)
//    {
//        webSocketServer.sendMessage(msg);
//    }

}
